/**
 * 
 */
package com.livemeter;

import com.livemeter.PollOption;
import com.livemeter.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;


/**
 *
 *Activity to show/activate available polls and topics.
 */
public class AnswerPollActivity extends Activity 
{
	private Poll currentPoll;
	private RadioGroup radioGroup;
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {   
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.answer_poll);
  
        this.radioGroup = (RadioGroup) this.findViewById(R.id.pollAnswersGroup);
  
        View closeButton = findViewById(R.id.pans_okButton);
        closeButton.setOnClickListener( new OnClickListener() {
        	public void onClick(View v)
        	{
            	if(AnswerPollActivity.this.currentPoll == null)
            		return;
            	
        		int checkedAnswer = AnswerPollActivity.this.radioGroup.getCheckedRadioButtonId();
        		
        		if(checkedAnswer == -1)
        		{
        			AlertDialog alertDialog;
        			alertDialog = new AlertDialog.Builder(AnswerPollActivity.this).create();
        			alertDialog.setTitle(AnswerPollActivity.this.getString(R.string.NoPollAnswer));
        			alertDialog.setMessage(AnswerPollActivity.this.getString(R.string.PollAnswerError));
        			alertDialog.show();
        			return;
        		}
        		
        		AnswerPollActivity.this.onAnswerPollClicked(checkedAnswer);
        	}
        } );
        

        View cancelButton = findViewById(R.id.pans_cancelButton);
        cancelButton.setOnClickListener( new OnClickListener() {
        	public void onClick(View v)
        	{
            	AnswerPollActivity.this.finish();
        	}
        } );
        
        Bundle extras = getIntent().getExtras();      
        currentPoll = Poll.getPoll(extras.getString("PollTitle"));
        
        if ((currentPoll != null) && (!currentPoll.isActive()))
        	currentPoll = null;
        
        if(currentPoll != null)
        {
        	TextView questionLabel = (TextView) this.findViewById(R.id.pans_pollQuestionLabel);
        	questionLabel.setText(currentPoll.getQuestion());
        }
        
        this.loadPollAnswers();

    	LIM_Engine lim = LIM_Engine.getInstance();
		lim.removeEventListener(m_clientLIMEventListener);
		lim.addEventListener(m_clientLIMEventListener);
    }
    
    LIM_Event_Listener m_clientLIMEventListener = new LIM_Event_Listener() {
		@Override
		public void meterValueChanged(LIM_MeterValueEvent evt) {}
		@Override
		public void pollOpened(LIM_PollEvent evt) {}
		@Override
		public void pollUpdated(LIM_PollEvent evt) {}
		@Override
		public void pollClosed(LIM_PollEvent evt) 
		{
			Log.i("LIM-APA", "closing poll: "+evt.poll.getTitle());
			if (evt.poll.getTitle().equalsIgnoreCase(currentPoll.getTitle()))
			{
				AnswerPollActivity.this.finish();
			}
		}
		@Override
		public void meterOpened(LIM_MeterEvent evt) {}
		@Override
		public void meterClosed(LIM_MeterEvent evt) {}
		@Override
		public void topicStamp(LIM_TopicStampEvent evt) {}
		@Override
		public void setupTimeout() {}
		@Override
		public void tick() {}
		@Override
		public void questionsChanged() {}
    };
    
    PowerManager.WakeLock wl = null;

    @Override
    protected void onResume() {
    	super.onResume();
    	currentPoll.setHasBeenShown();
    	//prevent standby
        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "LIM_IMA");
        wl.acquire();
    }
    @Override
    protected void onPause() {
    	//release standby
    	wl.release();
    	super.onPause();
    }
    /*
     * User answered to poll.
     * */
    private void onAnswerPollClicked(int indexAnswer) 
    {   	
    	Log.d("Poll answered", "index: " + indexAnswer);
    	
    	if(indexAnswer > this.currentPoll.getOptions(false).size() - 1)
    	{
    		Log.e("onAnswerPollClicked", "Index out of bounds: " + indexAnswer);
    		return;
    	}
    	
    	
    	//add a vote
    	
		//TODO: LIM_Engine : send Poll answer; the best way: in Poll class if possible.
    	LIM_Engine.getInstance().client_PollVoteFor(this.currentPoll, indexAnswer);
    	
    	//start activity to show poll results
    	if(this.currentPoll != null)
    	{
    		Intent intent = new Intent(Intent.ACTION_VIEW);
        	intent.setClassName(AnswerPollActivity.this, PollResultsActivity.class.getName());
        	intent.putExtra("PollTitle", this.currentPoll.getTitle());
        	startActivity(intent);  
    	}
    
    	//save poll vote to restore it next time
    	this.saveSettings(this.currentPoll.getTitle(), indexAnswer);
    	
    	this.radioGroup.removeAllViews();
    	this.finish();
	}
    

	/**
     * Converts dip to pixel
     *
     */
    public float convertDipToPixel(int dip) 
    {
    	return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, this.getResources().getDisplayMetrics());
    } 
    
    /*
     * Method sets up controls to display all possible answers for poll.
     * */
    private void loadPollAnswers()
    {
    	if(this.currentPoll == null)
    		return;
    	    	
    	
    	LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    	lp.setMargins(0, (int) convertDipToPixel(30), 0, 0);
    	
    	int i = 0;
    	
    	//add radioButtons for each possible answer
    	for(PollOption option : this.currentPoll.getOptions(false))
    	{
    		 RadioButton newRadioButton = new RadioButton(this);
    	     newRadioButton.setText(option.getOption());
    	     newRadioButton.setId(i);
    	     newRadioButton.setTextSize(15);
    	     
    	     this.radioGroup.addView(newRadioButton, i++, lp);
    	}
    	
    	if(this.currentPoll != null)
    		this.loadSettings(this.currentPoll.getTitle());
    }
    
    private void loadSettings(String pollTitle)
	{
		SharedPreferences settings = getSharedPreferences(pollTitle + "settings", 0);

		int pollOptionIndex = settings.getInt("polloption", -1);
		
		if(pollOptionIndex == -1) //no vote saved
			return;
		
		((RadioButton)this.radioGroup.getChildAt(pollOptionIndex)).setChecked(true);
	}
	
    private void saveSettings(String pollTitle, int pollOptionIndex)
	{
		SharedPreferences settings = getSharedPreferences(pollTitle + "settings", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("polloption", pollOptionIndex);
	
		// Commit the edits!
		editor.commit();
	}
}
